from openpyxl import load_workbook


class NumTypeError(Exception):
    '''
    '''

class DcmDidCfg(object):
    def __init__(self,didNum: str ='None',didDescr: str = '',didLen: int='0',didWriteEn: bool='FALSE',didReadEn: bool='FALSE',storeLoc: str='None') -> None:
        self.didNum = didNum
        self.didLen = didLen
        self.didReadEn = didReadEn
        self.didWriteEn = didWriteEn
        self.storeLoc = storeLoc
        self.didDescr = didDescr

def searchDidInfo(filePath):
    excel = load_workbook(filePath)
    sheet = excel[excel.sheetnames[0]]
    DidInfoList = []
    for row in sheet.iter_rows(min_row=2, max_row=sheet.max_row, min_col=1, max_col=sheet.max_column):  
        try:
            didNum = hex(is_number(row[0].value,16))[2:].upper()
        except ValueError:
            continue

        didDescr = row[1].value.split('\n')
        didDescr = didDescr[0]
        try:
            didLen = is_number(row[2].value,10)
        except ValueError:
            continue

        storeLoc = row[3].value
        didReadEn = row[4].value
        didWriteEn = row[5].value
        if didReadEn == 'Y':
            didReadEn = True
        else:
            didReadEn = False
        if didWriteEn == 'Y':
            didWriteEn = True
            storeLoc = 'EEPROM'
        else:
            didWriteEn = False
        if didWriteEn | didReadEn == False:
            continue
        DidInfoList.append(DcmDidCfg(didNum,didDescr,didLen,didWriteEn,didReadEn,storeLoc))
    return DidInfoList


def is_number(s,type:int):
    if isinstance(s, str):
        if s.strip().startswith('0x'):
            s1 = s.strip().split('0x',1)
            if len(s1) == 2 and s1[1].isnumeric:
                s = int(s1[1],16)
                return s
            else:
                raise NumTypeError('不是数字')
        else:
            try:
                s = int(s,16)
                return s
            except ValueError:
                raise NumTypeError('不是数字')
    else:
        while 1:
            return int(str(s),type)
